import React, { Component } from 'react'
//路由传参
import {withRouter} from "react-router-dom"
import {Bottom,InputItem,ImagePicker, WingBlank, SegmentedControl,Toast} from "antd-mobile"
import { Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import './orderInformation.scss'
import OrderVideo from '../../assets/img/order-video.png'
import OrderXj from '../../assets/img/order-xj.png'
import Correct from '../../assets/img/correct.png'
import Error from '../../assets/img/error.png'
import VideoMp4 from '../../assets/img/video.mp4'
import {throttle} from 'throttle-debounce'
import OrderStart from '../../assets/img/11.png'
import axios from 'axios'
import OrderError from '../../assets/img/orderError.png'
import { BASE_URL } from '../../utils/requestPath';
import requestAxios from '../../utils/myaxios'
import Jump from '../../assets/img/navigator_jump.png'
const uploadImage = BASE_URL+"/uploadPictures"
var time;
const data = [];
function getBase64(img, callback){
    console.log("-=-=-=-=-=-=-=-=--=--=")
    console.log(img)
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

//图片
function beforeUpload(file) {
    console.log("----------------------------------------------------------------")
    console.log(file)
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 5; //file.size / 1024 / 1024 < 2 小于2M  
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
}

//视频
function beforeUploadVideo(file) {
    console.log("----------------------------------------------------------------")
    console.log(file)
    const isJpgOrPng = file.type === 'video/mp4' || file.type === 'video/mp4';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 20; //file.size / 1024 / 1024 < 2 小于2M  
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
}


  
function beforeUploadText(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
}

class OrderInformation extends Component {
    
    state = {
        reSet:"<",
        dataflag:0,
        orderInputValue:"",
        message:"",
        files: data,
        multiple: false,
        dataList:[],
        loading: false,
        imagesList:[
          
        ],
        valueList:[

        ],
        canRun:false,
        orderStartImg:false,
        naviagtorOrderStart:false,
        JumpItem:false,
        clearNaviagtorOrderTop:true,
        naviagtorOrderStartTop:true,
        goodsIntegral:false,
        userInfoNew:{},
        orderId:300,
        integralCount:10000,  //积分
        integralGoodCount:1000, //日元
        
    }

    onChange = (files, type, index) => {
        console.log(files, type, index);
        this.setState({
            dataList:files
        });
    }

    onSegChange = (e) => {
        const index = e.nativeEvent.selectedSegmentIndex;
        this.setState({
          multiple: index === 1,
        });
      }

    handleClick = (params) => {
        this.props.history.push("/searchCenter");
    }
    
    escOnClick=()=>{
        this.props.history.goBack()
        //this.props.history.push("/navigator")
    }

    componentDidMount(){
       console.log(parseInt(new Date().getTime()))
       this.requestIntegralOrderJump()
       this.getOrderInfo()
    }

    //查询用户订单信息...
    getOrderInfo= async()=>{

        const userInfoIns =await localStorage.getItem("userInfoIns")
        const user = JSON.parse(userInfoIns) || {}
    
        await requestAxios.get(BASE_URL+"/api/order/info/"+parseInt(user.id)).then(res=>{
           if(!res.data){
               this.setState({
                 integralCount:1000,
                 integralGoodCount:100,
               })
           }else{
            this.setState({
                integralCount:10000,
                integralGoodCount:1000,
              })
           }
        })

        
    
      }

    inputOnClick = ()=>{
        console.log(this.state.orderInputValue)
        requestAxios.get(BASE_URL+"/api/order/find/"+this.state.orderInputValue).then(res=>{
            if(res.data.flag){
                this.setState({
                    dataflag:1,
                    message:res.data.message
                })
            }else{
                this.setState({
                    dataflag:2,
                    message:res.data.message
                })
            }
        })

    }

    InputOrderOnChange = (e)=>{
        this.setState({
            orderInputValue:e
        })

        // cart(e, 3, 5);
         throttle(3000, false, (e) => {

            
        
        });


    }
    handleChange = info => {
        console.log("点击了照片")
        console.log(info)
        if (info.file.status === 'uploading') {
          this.setState({ loading: true });
          return;
        }
        if (info.file.status === 'done') {

            console.log(info.file.response)
            let {imagesList} = this.state;
            let iamgesListAll = imagesList
            iamgesListAll.push(
                {
                    time:parseInt(new Date().getTime()),
                    url:"http://"+info.file.response
                }
            )
            
            this.setState({
                imagesList:iamgesListAll
            })

            console.log(iamgesListAll)
        }
      };
      handleChangeVideo = info => {
          console.log("点击了video")
        console.log(info)
        if (info.file.status === 'uploading') {
          this.setState({ loading: true });
          return;
        }
        if (info.file.status === 'done') {

            console.log(info.file.response)
            let {valueList} = this.state;
            let valueListAll = valueList
            valueListAll.push(
                {
                    time:parseInt(new Date().getTime()),
                    url:"http://"+info.file.response
                }
            )
            
            this.setState({
                valueList:valueListAll
            })

            //push 后的
            console.log(this.state.valueList)
            console.log(this.state.imagesList)
        }
      };

      onClickImages=(e)=>{
          console.log(e)
          console.log("dianji")
          const {imagesList} = this.state;
          imagesList.splice(e,1)
          this.setState({
              imagesList:imagesList
          })
      }

      onClickVideo=(e)=>{
        console.log(e)
        console.log("dianji")
        const {valueList} = this.state;
        valueList.splice(e,1)
        this.setState({
            valueList:valueList
        })
    }

    onClickStart= async ()=>{
        this.getOrderInfo()
        var dFlag = true;
        //get user info
        const zgUser = localStorage.getItem("userInfoIns");
        const zgUsers = JSON.parse(zgUser) || {};
        //上传的图片,,,用户id,mobx ,,,订单号,,,,,订单提交成功得到多少积分


        const userId = zgUsers.id;
        const {imagesList,orderInputValue} = this.state;
        if(orderInputValue.length > 30){
            Toast.info('输入有误', 2, null, false);
            return;
        }

        //1,先判断订单号是否正确
        await requestAxios.get(BASE_URL+"/api/order/find/"+orderInputValue).then(res=>{
             //debugger
            if(!res.data.flag){
                //如果为false ,那么订单信息有误
                dFlag = false;
                Toast.info('没有这个订单号或订单号已使用', 2, null, false);
                return;
            }
        })

        //判断订单号是否被使用
        if(dFlag){
            Toast.loading('Loading...', 2, () => {
                console.log('Load complete !!!');
            });
            let images = "";
            console.log(imagesList)
            for (let i = 0; i < imagesList.length; i++) {
                  console.log(imagesList[i].url)
                   images += imagesList[i].url +","          
            }
            
            //提交订单号并修改订单号状态
            let id = parseInt(userId);
            let orderNo = orderInputValue;
            let orderImages = images;
            let type = 1;
            const userInfoOrder = {id,orderNo,orderImages,type};
            setTimeout(() => {
                console.log(userInfoOrder)
                //2,如果订单号正确,那么提交请求,并增加积分
                requestAxios.post(BASE_URL+"/api/order/add/start",userInfoOrder).then(res=>{
                    if(res.data.flag){
                        //订单i信息提交成功,跳转到礼物中心/或个人中心,并弹出提示框
                        //弹出,恭喜您
                        this.setState({
                            orderStartImg:true
                        })
                    }
                })
                
                console.log("打印输入对象------------")
                console.log(userInfoOrder)
                console.log("提交订单请求")
            }, 2000);
        }
        

    }
    orderErrorOnClick = ()=>{
        this.setState({
            orderStartImg:false
        })
        console.log("关闭......")
    }

    lwOnClick = ()=>{

        this.props.history.push("/navigator")

    }

    handleChangeText = info => {
        if (info.file.status === 'uploading') {
          this.setState({ loading: true });
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          getBase64(info.file.originFileObj, imageUrl =>
            this.setState({
              imageUrl,
              loading: false,
            }),
          );
        }
      };

      onChangeImage = (files, type, index) => {
        console.log(files, type, index);
        this.setState({
          files,
        });
      }

      uploadClick = ()=>{
          console.log("点击了.......")
      }

      

      requestIntegralOrderJump=()=>{
        const userInfoIns = localStorage.getItem("userInfoIns")
        const user = JSON.parse(userInfoIns) || {}
        
        requestAxios.get(BASE_URL+"/api/user/getid/"+user.id).then(res=>{
            //debugger
            if(res.data.jumpStart !== 1){
              this.setState({
                naviagtorOrderStart:true,
                JumpItem:true
              })
            }
        })
      }

      //跳过引导........发送请求...后台,同时关闭页面向导
      clearNaviagtorOrderTop=()=>{
        this.setState({
            JumpItem:false
        })
      }
    
    
      naviagtorOrderStart = ()=>{
          this.setState({
            naviagtorOrderStart:false,
            // clearNaviagtorOrderTop:true,
            // naviagtorOrderStartTop:true,
          })
      }

      //步骤一,用户输入订单号后进行下一步操作
      naviagtorOrderStartTop = ()=>{
          //判断用户是否输入了订单号
          if(this.state.orderInputValue.length > 7){
            this.setState({
                naviagtorOrderStartTop:false,
                orderId:3
            })
          }
      }

      //步骤二,上传图片的下一步
      naviagtorOrderStartTopTwo=()=>{
          console.log(313131)
      }

      //步骤三:提交请求
      naviagtorOrderStartTopThree=()=>{
          console.log(234234)
      }


    render() {
        const {reSet,loading, imageUrl,files} = this.state
        const uploadButton = (
            <div style={{flexDirection:"column",alignItems:"center"}}>
              {/* {loading ? <LoadingOutlined /> : <PlusOutlined />} */}
              <img src={OrderXj} style={{width:40,height:40}}></img>
              <div style={{ marginTop: 8 ,fontWeight:"800"}}>アップロードする</div>
            </div>
          );

          const uploadButtonVideo = (
            <div style={{flexDirection:"column",alignItems:"center"}}>
              {/* {loading ? <LoadingOutlined /> : <PlusOutlined />} */}
              <img src={OrderVideo} style={{width:40,height:40}}></img>
              <div style={{ marginTop: 8 ,fontWeight:"800"}}>添加视频</div>
            </div>
          );

          const uploadButtonTexe = (
            <div>
              {loading ? <LoadingOutlined /> : <PlusOutlined />}
              <div style={{ marginTop: 8 }}>Upload</div>
            </div>
          );
        return (
            <div className="main-order-app">
                {/* 头部,返回,评价 */}
                <header className="main-order-header">
                    <div className="main-order-header-con" onClick={this.escOnClick}>
                        <span className="main-order-header-con-span-one">{reSet}</span>
                        <span  className="main-order-header-con-span-two">戻る</span>
                    </div>
                    <h4>
                    レビューを書く
                    </h4>
                </header>

                {/* 店铺名称.....及订单号 */}
                <main className="main-order-con">
                    {/* 内部内容 */}
                    <section className="main-order-top">
                    {/* 名称及订单号 */}
                    <h4>店舗名</h4>
                    <div className="main-order-id" style={{zIndex:`${this.state.orderId}`}}>
                         {/* <h4>输入订单号</h4> */}
                         <InputItem
                         style={{width:200}}
                            placeholder="请输入订单号"
                            labelNumber={100}
                            onChange={this.InputOrderOnChange}
                        >注文番号</InputItem>
                        
                    </div>
                    <span className="main-order-information-message">アマゾン/楽天/Yahooの商品レビューのスクリーンショットを添付してください...</span>
                    {/* 照片以及添加视频 */}
                    <div className="main-order-img-and-video">
                        <article 
                        onClick={this.uploadClick}
                        className="main-order-img">
                        <Upload
                                name="file"
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action={uploadImage}
                                beforeUpload={beforeUpload}
                                onChange={this.handleChange}
                            >
                                {/* {this.state.imagesList.length >= 2 ? <img src={OrderXj} style={{ width: '100%' }} alt="avatar" ></img> : uploadButton} */}
                                {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%',height:"100%"  }} /> : uploadButton}
                            </Upload>
                        </article>

                        {/* <article className="main-order-video">
                        <Upload
                                name="file"
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action={uploadImage}
                                beforeUpload={beforeUploadVideo}
                                onChange={this.handleChangeVideo}

                            >
                                {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%',height:"100%" }} /> : uploadButtonVideo}
                            </Upload>
                        </article> */}

                        {/* <article className="main-order-video">
                        <Upload
                            name="avatar"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                            beforeUpload={beforeUploadText}
                            onChange={this.handleChangeText}
                        >
                            {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButtonTexe}
                        </Upload>
                        </article> */}

                        {/* <article className="main-order-video"
                        >
                            <ImagePicker
                            files={files}
                            onChange={this.onChangeImage}
                            onImageClick={(index, fs) => console.log(index, fs)}
                            selectable={files.length < 7}
                            multiple={this.state.multiple}
                            />
                        </article> */}

                    </div>

                    {/* 留个空地址用来存放图片 */}
                    <div className="main-order-imgs">
                       {this.state.imagesList.map((value,index)=>{
                           return (
                               <div key={index} style={{position:"relative",marginLeft:9}}>
                                   <div 
                                   onClick={this.onClickImages.bind(this,index)} 
                                   style={{position:"absolute",right:2,top:2,
                                   display:"block",width:10,height:10,}}
                                   >X</div>
                                   <img style={{width:80,height:80,marginLeft:10,marginBottom:10}} src={value.url}></img>
                               </div>    
                           )
                       })}
                    </div>

                    <div className="main-order-video-list">
                        {this.state.valueList.map((value,index)=>{
                            return (
                                <div key={index} style={{position:"relative",marginLeft:9}}>
                                    <div 
                                    onClick={this.onClickVideo.bind(this,index)} 
                                    style={{position:"absolute",right:2,top:2,
                                    display:"block",width:10,height:10,}}
                                    >X</div>
                                    <video 
                                        autoPlay
                                        style={{width:120,height:120}} 
                                        src={value.url}>
                                    </video>
                                </div>    
                            )
                        })}

                        {/* <video 
                        autoPlay
                        style={{width:120,height:120}} 
                        src={VideoMp4}>
                       </video> */}
                      
                     
                    </div>

                    {/* 如果超过5张..... */}
                    {/* <p>拍摄<span className="span1">5</span>张图片有机会被选为<span className="span2">优质评价</span></p> */}
                    {/* ---------------------------------------------------------- */}

                    {/* 活动规则 */}
                    <div className="main-order-activity-rules">
                        <h2>ルール</h2>
                        <div className="main-order-activity-right">
                            <h4>1,五つの星で評価</h4>
                            <h4>2,評価には「評価を書いてお金をもらう」書いてないてください</h4>
                            <h4>3,24時間以内にポイントを</h4>
                        </div>
                    </div>
                    </section>

                    {/* 提交请求 */}
                    <div className="footerInputCon" onClick={this.onClickStart}>
                     <input className="footerInput" type="button" value="保存して終了"></input>
                    </div>

                </main>

                {this.state.orderStartImg?<div style={{position:"absolute",width:"100%",overflow:"scroll",marginBottom:20,
                height:"100vh",background:"#fff",paddingTop:70,zIndex:1000,
                display:"flex",flexDirection:"column",
                alignItems:"center",justifyContent:"space-around"}}>
                    <div style={{height:42,width:240,background:"rgb(229, 60, 57)",
                    borderRadius:5,display:"flex",flexDirection:"row",
                    justifyContent:"center",alignItems:"center",}}>
                        <h4 style={{width:182,height:26,
                            alignItems:"center",
                            lineHeight:"22px",
                            color:"rgb(245, 245, 245)",
                            borderRadius:30,textAlign:"center",fontSize:28,fontWeight:400}}>本物確認</h4>
                    </div>       
                    <div style={{position:"relative",width:"100%",height:380,display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center"}}>
                        <div style={{position:"absolute",display:"flex",flexDirection:"column",alignItems:"center",height:380,width:"100%"}}>
                            <h2 style={{color:"rgb(230, 60, 57)",lineHeight:2,marginTop:70,fontSize:18,}}>良い評価投稿すると</h2>
                            <h3 style={{color:"rgb(230, 60, 57)",lineHeight:2,marginTop:5}}><span style={{fontSize:28,letterSpacing:2,fontWeight:"bold"}}>{this.state.integralCount}</span>积分</h3>
                            <h4 style={{color:"rgb(230, 60, 57)",lineHeight:2,marginTop:5}}>即{this.state.integralGoodCount}円</h4>
                            <h5 style={{color:"rgb(230, 60, 57)",
                            lineHeight:1.9,marginTop:68,fontSize:18,
                            height:36,width:84,background:"rgb(250, 200, 13)",borderRadius:8,textAlign:"center"}}>会員限定</h5>
                        </div>    
                        <img src={OrderStart}>
                            
                        </img>
                    </div>    
                    
                    <h3 onClick={this.lwOnClick} style={{width:217,height:36,background:"rgb(229, 60, 57)",borderRadius:14,lineHeight:2.8,color:"#fff",textAlign:"center"}}>
                    ポイントの使用へ
                    </h3> 

                    <div onClick={this.orderErrorOnClick} style={{width:45,height:45,borderRadius:45,background:"#fff",border:"#000",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center"}}>
                        <img style={{width:40,height:40}} src={OrderError}></img>
                    </div>       
                </div>:""}
                {this.state.JumpItem?
                    <div className="navigator-guide-page-order">
                        {this.state.naviagtorOrderStart? <p className="navigator-guide-page-img-order">
                        {/* <img src={Jump}></img> */}
                    </p>:""}
                        <div className="naviagtor-guide-page-right-order">
                        </div>
                        {this.state.naviagtorOrderStartTop?
                        <div className="navigator-guide-page-order-top-order"> 
                        {/* 箭头 */}
                        <p className="navigator-guide-page-order-input-order">
                            <img src={Jump}></img>
                        </p>
                        {/* 次に進む */}
                        <div className="navigator-good-clear-order"> 
                            <h4 className="naviagtor-good-clear-order-order" onClick={this.clearNaviagtorOrderTop}>スキップ</h4>
                            <h3 className="navigator-good-clear-ok-order" onClick={this.naviagtorOrderStartTop}>次に進む</h3>
                            <p className="naviagtor-guide-page-good-message-order">クリックすると、ポイントをもらう:クリックするとポイントをもらうページへ,レビューを書く、积分をもらう

                            </p>
                        </div>
                        </div>:""  
                        }
                         {/* 步骤二:上传图片开始 */}
                        {this.state.twoOrderStart?
                            <div className="navigator"> 
                                <p className="navigator-guide-page-order-input-order">
                                    <img src={Jump}></img>
                                </p>
                                <div className="navigator-good-clear-order"> 
                                    <h4 className="naviagtor-good-clear-order-order" onClick={this.clearNaviagtorOrderTop}>スキップ</h4>
                                    <h3 className="navigator-good-clear-ok-order" onClick={this.naviagtorOrderStartTopTwo}>次に進む</h3>
                                    <p className="naviagtor-guide-page-good-message-order">クリックすると、ポイントをもらう:クリックするとポイントをもらうページへ,レビューを書く、积分をもらう
                                    </p>
                                </div>
                            {/* 上传图片结束 */}
                         </div>:""       
                    }

                        {/* 步骤三:提交请求 */}
                        {this.state.threeOrderStart?
                            <h3 className="navigator-good-clear-ok-order" onClick={this.naviagtorOrderStartTopThree}>次に進む</h3>:""
                        }
                        {/* 提交请求结束 */}                        

                        
                    </div>:"" 
                }

            </div>
        )
    }
}
export default withRouter(OrderInformation)
